import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Login from '@/views/login'
import Myorder from '@/views/myorder'
import Pay from '@/views/pay'
import Prodetail from '@/views/prodetail'
import Search from '@/views/search'
import SearchList from '@/views/search/list'
import Home from '@/views/layout/home'
import Cart from '@/views/layout/cart'
import Category from '@/views/layout/category'
import User from '@/views/layout/user'
import store from '@/store'
Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    component: Layout,
    children: [
      { path: '/home', component: Home },
      { path: '/category', component: Category },
      { path: '/cart', component: Cart },
      { path: '/user', component: User }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/myorder',
    component: Myorder
  },
  {
    path: '/pay',
    component: Pay
  },
  // 动态路由传参，确认是哪一个商品，路由参数中携带id
  {
    path: '/prodetail',
    component: Prodetail
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/searchlist',
    component: SearchList
  },
  {
    path: '/*',
    redirect: '/'
  }
]

const router = new VueRouter({
  routes
})

// 全局前置导航守卫
// to  ：到哪里去
// from ：从哪里来
// next ：是否放行
// (1)next()  直接放行，放行到to指定的路径
// (2)next(路径)  进行拦截，拦截到next中配置的路径

// 用于存放需要权限访问的页面
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
// 需要判断to.path是否在authUrls中
  if (!authUrls.includes(to.path)) {
  // 非权限页面，直接放行
    next()
    return
  }
  // 权限页面  需要判断是否有token
  const token = store.getters.token
  // console.log(token)
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
